from PyQt5 import QtCore, QtGui, QtWidgets
import sys, os
from editor import Text_Editor
import pandas as pd
from SLP_python_terminal import out_command_line
from variable_list import var_list_widget
from modules import var_test_module, cor_test_module, describe_stat_module

class main_GUI(QtWidgets.QMainWindow):
    """
    main window class
    """

    def __init__(self):
        
        super(main_GUI, self).__init__()
        self.editor_dict = dict()
        self.cur_data = pd.DataFrame()
        self.initUI()
    
    def initUI(self):
        self.main_widget = QtWidgets.QWidget()
        self.setCentralWidget(self.main_widget)
        spliter = QtWidgets.QSplitter()
        HLayout_1 = QtWidgets.QHBoxLayout()
        self.resize(1200, 800)
            
        self.sub_windows_manage = QtWidgets.QMdiArea()
        self.sub_windows_manage.setWindowIcon(QtGui.QIcon("logo_ico.ico"))

        self.outcmd = out_command_line()
        self.sub_windows_manage.addSubWindow(self.outcmd)
        self.sub_windows_manage.subWindowList()[-1].resize(800,550)

        # Set window title
        self.setWindowTitle("SLP: Statisticas Learn Package - GUI")
        self.setWindowIcon(QtGui.QIcon("logo_ico.ico"))

        self.statusBar()

        self.file = self.menuBar().addMenu("文件")
        
        self.open = QtWidgets.QAction('打开')
        self.open.triggered.connect(self.open_file)
        self.load_data = QtWidgets.QAction('导入数据')
        self.load_data.triggered.connect(self.open_file)

        self.file.addAction(self.open)
        self.file.addAction(self.load_data)



        self.menu_stat_button = self.menuBar().addMenu("分析")
        self.setting_menu_stat_button()

        self.var_list = var_list_widget()

        spliter.addWidget(self.outcmd)
        spliter.addWidget(self.var_list)
        spliter.setStretchFactor(0,1)
        HLayout_1.addWidget(spliter)

        self.main_widget.setLayout(HLayout_1)
        self.show()

    def setting_menu_stat_button(self):
        describe_stat_menu = self.menu_stat_button.addMenu('描述性统计')
        describe_data = QtWidgets.QAction('基本描述统计', self)
        cross_table = QtWidgets.QAction('交叉表', self)
        describe_stat_menu.addAction(describe_data)
        describe_stat_menu.addAction(cross_table)

        describe_data.triggered.connect(self.open_describe_stat_module)
        self.menu_stat_button.addMenu(describe_stat_menu)
        
        self.menu_stat_button.addAction("线性模型")

        mu_test_menu = self.menu_stat_button.addMenu("均值检验")
        single_t = QtWidgets.QAction('单样本t检验', self)
        mu_test_menu.addAction(single_t)

        var_test_action = QtWidgets.QAction('方差比检验', self)
        var_test_action.triggered.connect(self.open_var_test_module)
        self.menu_stat_button.addAction(var_test_action)

        cor_test_action = QtWidgets.QAction('相关系数检验', self)
        cor_test_action.triggered.connect(self.open_cor_test_module)
        self.menu_stat_button.addAction(cor_test_action)

        #cross_table = QtWidgets.QAction('交叉表', self)
        #self.menu_stat_button.addAction(cross_table)

    def open_var_test_module(self):
        self.var_test_dialog = var_test_module.var_test_dialog()
        self.var_test_dialog.show()

    def open_cor_test_module(self):
        """打开相关系数检验模块"""
        self.cor_test_dialog = cor_test_module.cor_test_dialog(self.cur_data)
        if self.cur_data.empty:
            self.cor_test_dialog.init_var_select_box([])
        else:
            self.cor_test_dialog.init_var_select_box(self.cur_data.columns.tolist())


        self.cor_test_dialog.out_come_signal.connect(self.outcmd.add_out_info)
        self.cor_test_dialog.show()

    def open_describe_stat_module(self):
        self.describe_stat = describe_stat_module.describe_stat_dialog(self.cur_data)
        self.describe_stat.out_come_signal.connect(self.outcmd.add_out_info)

        self.describe_stat.show()
    def init_dataset_manager(self, file_path):
        """读入数据"""
        self.cur_data = pd.read_excel(file_path)
        """读取变量名与变量类型（每一列为一个变量）"""
        for i in range(len(self.cur_data.columns)):
            self.var_list.add_items_by_row([self.cur_data.columns[i],self.cur_data.dtypes[i]])

    def open_file(self):
        path = os.getcwd()
        try:
            file_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "打开", path,
                                        "All Files(*);;Excel(.xlsx);;Python Source(*.py);;Text Files(*.txt)")
            str_file_path = file_path.__str__()
            pos = str_file_path.rfind('.')
            file_type = str_file_path[pos:]
            if file_type in [".py", ".txt"]:
                py_Editor = Text_Editor(str_file_path)
                py_Editor.load_file() 
                if py_Editor.windowTitle() not in self.editor_dict.keys():
                    self.editor_dict[py_Editor.windowTitle()] = py_Editor

                    cur_editor = self.editor_dict[py_Editor.windowTitle()]
                    cur_editor.resize(1200,1500)
                    cur_editor.show()
            elif file_type in '.xlsx':
                self.init_dataset_manager(str_file_path)
        except Exception as e:
            print(e)
    

        
    def closeEvent(self,event):
        super().closeEvent(event)


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)

    main = main_GUI()
    app.setWindowIcon(QtGui.QIcon("logo_ico.ico"))
    sys.exit(app.exec_())


